<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>Layui</title>
    <meta name="renderer" content="webkit">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css"  media="all">
    <link rel="stylesheet" href="https://cdn.bootcdn.net/ajax/libs/zTree.v3/3.5.40/css/zTreeStyle/zTreeStyle.css" type="text/css">
    <link rel="stylesheet" href="https://www.layuicdn.com/layui-v2.5.6/css/layui.css" type="text/css">
    <script type="text/javascript" src="https://www.layuicdn.com/layui-v2.5.6/layui.all.js"></script>
    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
    <script type="text/javascript" src="https://cdn.bootcdn.net/ajax/libs/zTree.v3/3.5.40/js/jquery.ztree.all.min.js"></script>
    <style type="text/css">
        .layui-tab-title {
            position: static;
            height: 28px;
            line-height: 28px;
        }
        .layui-tab-title li {
            position: static;
            padding: 0 8px;
            line-height: 28px;
            border:2px solid #fff;
        }
        .layui-tab .layui-tab-content{
            height: calc(100% - 37px) !important;
        }
        .layui-show {
            height: 100%;
        }
        .layui-body {
            left: 300px;
        }
        ul.ztree {
            border: 1px solid #617775;
            background: #f0f6e4;
            /*width:300px;*/
            /*height:360px;*/
            overflow-y:scroll;
            overflow-x:auto;
        }
        .ztree li span.button.add {
            margin-left:2px;
            margin-right: -1px;
            background-position:-144px 0;
            vertical-align:top;
            *vertical-align:middle
        }
    </style>
    <script LANGUAGE="JavaScript">
        jQuery.browser = {};
        (function() {
            jQuery.browser.msie = false;
            jQuery.browser.version = 0;
            if (navigator.userAgent.match(/MSIE ([0-9]+)\./)) {
                jQuery.browser.msie = true;
                jQuery.browser.version = RegExp.$1;
            }
        })();
        var layer = layui.layer;
        var form = layui.form;
        var setting = {
            view: {
                addHoverDom: addHoverDom,
                removeHoverDom: removeHoverDom,
                selectedMulti: false
            },
            edit: {
                enable: true,
                isMove: true,
                editNameSelectAll: true,
                showRemoveBtn: showRemoveBtn,
                showRenameBtn: true
            },
            data: {
                simpleData: {
                    enable: true,
                    idKey: "id",
                    pIdKey: "pId",
                    rootPId: null
                }
            },
            callback: {
                onDrop: onDrop,  // 用于捕获节点拖拽操作结束的事件回调函数  默认值： null
                beforeDrag: beforeDrag,
                beforeRemove: beforeRemove,
                beforeRename: beforeRename
            }
        };

        var zNodes =[ ];

        // 只允许同级节点拖拽的判断是什么
        function beforeDrag(treeId, treeNodes) {
            return true;
        }

        function onDrop(event, treeId, treeNodes, targetNode, moveType) {
            //拖拽成功时，修改被拖拽节点的pid
            console.log(event);
            console.log("拖动的节点ID  "+treeNodes[0].id+" 名称  "+treeNodes[0].name)
            console.log(treeNodes); //
            console.log(treeNodes[0].pId);
            console.log(targetNode);
            console.log(moveType);  // prev, inner, next
            // 该节点ID, 目标节点ID, moveType
            console.log("\n\n");
        }

        function beforeRemove(treeId, treeNode) {
            layer.confirm("确认删除 节点 -- " + treeNode.name + " 吗？", {
                btn: ['确定', '取消'] ,
                // btn: ['按钮1', '按钮2']
                btn1: function (index) {
                    // 按钮1的事件
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    zTree.removeNode(treeNode);
                    layer.close(index);
                },
                btn2: function(index) {
                    // 按钮2的事件
                    layer.close(index);
                }
            });
            return false;
        }

        function beforeRename(treeId, treeNode, newName, isCancel) {
            if (newName.length == 0) {
                setTimeout(function() {
                    var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                    zTree.cancelEditName();
                    layer.msg('节点名称不能为空', {
                        time: 1000 //2秒关闭（如果不配置，默认是3秒）
                    }, function() {
                        //do something
                    });
                }, 0);
                return false;
            }
            return true;
        }

        function showRemoveBtn(treeId, treeNode) {
            return treeNode.children==null;
        }

        var newCount = 1;
        function addHoverDom(treeId, treeNode) {
            var sObj = $("#" + treeNode.tId + "_span");
            if (treeNode.editNameFlag || $("#addBtn_" + treeNode.tId).length > 0) return;
            var addStr = "<span class='button add' id='addBtn_" + treeNode.tId + "' title='add node' onfocus='this.blur();'></span>";
            sObj.after(addStr);
            var btn = $("#addBtn_" + treeNode.tId);
            if (btn) btn.bind("click", function() {
                layer.open({
                    type: 1, //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                    title: "修改采集设备信息",
                    area: ['320px', '200px'],
                    content: $("#addTreeItem")//引用的弹出层的页面层的方式加载修改界面表单
                });

                // var zTree = $.fn.zTree.getZTreeObj("treeDemo");
                // zTree.addNodes(treeNode, {
                //     id: (100 + newCount),
                //     pId: treeNode.id,
                //     name: "new node" + (newCount++)
                // });
                // console.log(JSON.stringify(assemblyTreeData(zTree.getNodes()))+"\n\n\n");
                return false;
            });
        }

        function removeHoverDom(treeId, treeNode) {
            $("#addBtn_" + treeNode.tId).unbind().remove();
        }

        $(function() {
            $.fn.zTree.init($("#treeDemo"), setting, zNodes);
        })

        // 添加顶层节点
        function addTopLevelNode() {
            layer.open({
                type: 1, //layer提供了5种层类型。可传入的值有：0（信息框，默认）1（页面层）2（iframe层）3（加载层）4（tips层）
                title: "修改采集设备信息",
                area: ['320px', '200px'],
                content: $("#addTreeItem")//引用的弹出层的页面层的方式加载修改界面表单
            });
            var zTree = $.fn.zTree.getZTreeObj("treeDemo");
            zTree.addNodes(null, {
                id: (100 + newCount),
                pId: null,
                name: "new node" + (newCount++)
            });
            // layer.msg("点击事件");
        }

        function assemblyTreeData(treeNodes) {
            var newTreeNodes = [];
            for (var i in treeNodes) {
                var item = treeNodes[i];
                var newItem = {
                    "id": item["id"],
                    "name": item["name"],
                    "pId": item["pId"]
                };
                if (item.children!=null && item.children.length > 0) {
                    newItem["children"] = assemblyTreeData(item.children)
                }
                newTreeNodes.push(newItem);
            }
            return newTreeNodes;
        }

        var element = layui.element; //Tab的切换功能，切换事件监听等，需要依赖element模块
        function tabAdd() {
            //新增一个Tab项
            var id = new Date().getTime();
            element.tabAdd('tabPane', {
                title: '新选项'+ (Math.random()*1000|0) //用于演示
                ,content: '<iframe frameborder="0" height="100%" width="100%" scrolling="auto" src="./dynamicTable.html"></iframe>'
                ,id: id  //实际使用一般是规定好的id，这里以时间戳模拟下
            });
            element.tabChange('tabPane', id);
        }

        //新增一行
        form.on('submit(demo11)', function(data) {
            parent.layer.closeAll();
            $("#addTreeItem").attr("style","display:none;");//隐藏div
            return false;
        });
    </script>
</head>
<body>
<div style="padding:8px 8px;">
    <button type="button" class="layui-btn layui-btn-xs" onclick="addTopLevelNode()" style="margin-bottom:8px;">添加根节点</button>
    <ul id="treeDemo" class="ztree" style="width: 265px;"></ul>
</div>
<div class="layui-body">
    <div class="site-demo-button" style="margin-bottom: 0;">
        <button class="layui-btn site-demo-active" onclick="tabAdd()">新增Tab项</button>
    </div>

    <div class="layui-tab layui-tab-card" lay-filter="tabPane" lay-allowclose="true" style="height: 100%;margin: 0px;overflow: hidden;">
        <ul class="layui-tab-title"></ul>
        <div class="layui-tab-content"></div>
    </div>
</div>
<div class="layui-row" id="addTreeItem" style="display:none;">
    <div class="layui-col-md10">
        <form class="layui-form layui-from-pane" action="" style="margin-top:20px" >
            <div class="layui-form-item">
                <label class="layui-form-label">节点名称</label>
                <div class="layui-input-block">
                    <input type="text" name="neweqptName"  required  lay-verify="required" autocomplete="off" placeholder="请输入采集设备名称" class="layui-input">
                </div>
            </div>

            <div class="layui-form-item" style="margin-top:40px">
                <div class="layui-input-block">
                    <button class="layui-btn  layui-btn-submit " lay-submit="" lay-filter="demo11">确认</button>
                </div>
            </div>
        </form>
    </div>
</div>

</body>
</html>